package com.sk.leetcode.arithmetic.test1_10;

import java.util.Arrays;
import java.util.Objects;

/**
 * 给定一个字符串 s，找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
 * <p> 回文，要注意，我第一次理解错了
 * 输入: "babad"
 * 输出: "bab"
 * 注意: "aba"也是一个有效答案。
 */
public class Test5 {
    public static void main(String[] args) {
        String str = longestPalindrome("dd");
        System.out.println(str);
    }

    private static String longestPalindrome(String s) {
        String[] strings = s.split("");
        int start = 0, end = 0, num = 0;
        int len = strings.length;
        for (int i = 0; i < len; i++) {
            boolean b = true, c = true;
            int num1 = 0, num2 = 0;
            int n = i, m = i + 1;
            int p = i - 1, d = i + 1;
            while (b || c) {
                if(n >= 0 && m < len && (Objects.equals(strings[n], strings[m]))) {
                    n--;
                    m++;
                } else {
                    if(b) {
                        n++;
                        m--;
                        b = false;
                        num1 = m - n;
                    }
                }
                if(p >= 0 && d < len && (Objects.equals(strings[p], strings[d]))) {
                    p--;
                    d++;
                } else {
                    if(c) {
                        p++;
                        d--;
                        c = false;
                        num2 = d - p;
                    }
                }
            }
            int num0 = 0, start0 = 0, end0 = 0;
            if(num1 > num2) {
                num0 = num1;
                start0 = n;
                end0 = m;
            } else {
                num0 = num2;
                start0 = p;
                end0 = d;
            }
            if(num0 > num) {
                num = num0;
                start = start0;
                end = end0;
            }
        }
        int dis = 0, start1 = 0;
        for (int i = 0; i < len; i++) {
            if((i+1)<len){
                if(Objects.equals(strings[i],strings[i+1])){
                    if(dis == 0){
                        start1 = i;
                    }
                    dis++;
                }else{
                    if(dis>num){
                       start = start1;
                       end = i+1;
                    }
                    dis = 0;
                }
            }
        }

        return String.join("", Arrays.copyOfRange(strings, start, end+1));
    }
}
